<?php

namespace app\common\business;

use app\common\lib\Arr;
use app\common\lib\Curl;
use app\common\lib\Str;
use app\common\model\mysql\SystemCategory;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\Model;

class Department
{
    public $model = null;

    public function __construct()
    {
        $this->model = new \app\common\model\mysql\Department();
    }

    public function getListByWhere($where,$page,$limit,$field='*'){
        $where[] = ['status','=',config("status.mysql.table_normal")];
        if ($page!=0 && $limit !=0){
            $list = $this->model->getPageListByWhere($where,$page,$limit,$field);
        }else{
            $list = $this->model->getNormalListByWhere($where,$field);
        }
        if($list->isEmpty()){
            return [];
        }
        return $list->toArray();
    }

    /**
     * 获取分页列表
     * @throws Exception
     */
    public function getTableList($page=null,$limit=null,$keyword='',$status=null): array
    {
        $where=[
            ['name','like','%'.$keyword.'%']
        ];
        if($status===0||!empty($status)){
            $where[]=['status','=',$status];
        }
        return $this->model->getTableList($where,$page,$limit);
    }

    /**
     * @param $id
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getNormalById($id)
    {
        $data = $this->model->getById($id);
        if (!$data || $data->status != config("status.mysql.table_normal")) {
            return [];
        }
        return $data->toArray();
    }

    /**
     * @param $name
     * @return array
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function getNormalByName($name)
    {
        $data = $this->model->getNormalByField('name',$name);
        if (!$data) {
            return [];
        }
        return $data->toArray();
    }

    /**
     * 新增/保存数据
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException|Exception
     */
    public function save($data): bool
    {
        if(empty($data['id'])){
            unset($data['id']);

            //添加 单位名称不可重复
            $isExist = $this->getNormalByName(trim($data['name']));
            if (!empty($isExist)){
                throw new Exception('该单位已存在，请勿重复添加');
            }
        }
        return $this->model->saveData($data);
    }

    /**
     * 根据id修改状态
     * @param $data
     * @return bool
     * @throws DataNotFoundException
     * @throws DbException
     * @throws Exception
     * @throws ModelNotFoundException
     */
    public function updateStatus($data): bool
    {
        if(empty($data['id'])){
            throw new Exception('参数错误');
        }
        return $this->model->updateStatus($data);
    }

    /**
     * 根据id删除
     * @param $id
     * @return bool
     * @throws Exception
     */
    public function deleteById($id): bool
    {
        if(empty($id)){
            throw new Exception('参数错误');
        }
        return $this->model->deleteById($id);
    }

    /**
     * @param $condition
     * @return bool
     * @throws Exception
     */
    public function deleteByCondition($condition){
        if (empty($condition)){
            throw new Exception('参数错误');
        }

        return $this->model->where($condition)->delete();
    }

    /**
     * @param $data
     * @return \think\Collection
     * @throws Exception
     */
    public function saveAll($data){
        if (empty($data)){
            throw new Exception('参数错误');
        }

        return $this->model->saveAll($data);
    }

    /**
     * 获取就业部门数据
     * @param $data
     * @return bool|string
     */
    public function getCurlDList($data){
        $url = 'http://localhost:8069/getIntermediaryList';
        //$url = 'https://www.adhrsp.com/getIntermediaryList';
        $url.='?page='.$data['page'].'&limit='.$data['limit'];

        $result = Curl::curlGetContents($url);
        return $result;
    }

    /**
     * 通过就业人力资源公司数据更新department表
     * @param $curlData
     * @return bool
     * @throws Exception
     */
    public function updateByCurlData($curlData){
        if (empty($curlData)){
            throw new Exception('就业平台人力资源数据获取失败1');
        }

        $curlData = json_decode($curlData);
        $curlData = Str::object2array($curlData);
        if (!isset($curlData['data']['list'])){
            throw new Exception('就业平台人力资源数据获取失败2');
        }
        if (empty($curlData['data']['list'])){
            throw new Exception('就业平台人力资源数据获取失败3');
        }

        //测试
        foreach ($curlData['data']['list'] as $k=>$v){
            if(in_array($v['id'],[16,14])){
                //unset($curlData['data']['list'][$k]);
            }
        }

        //初始化需变动数据
        $saveNew = [];
        $addNew = [];

        //本批次就业人资数据
        $curlDataArr = [];
        $curlDataNameArr = [];
        $curlDataIdArr = array_column($curlData['data']['list'],'id');
        $curlDataNameKeyArr = array_column($curlData['data']['list'],'name');
        foreach ($curlData['data']['list'] as $k=>$v){
            $curlDataArr[$v['id']] = $v;
            $curlDataNameArr[$v['name']] = $v;
        }
        //dump($curlDataNameKeyArr,$curlDataNameArr);exit;

        //查询库中现有的就业端人力资源公司数据
        $map = [
            //['out_id','<>',0]
        ];
        $currentData = (new \app\common\model\mysql\Department())->where($map)->field('id,name,status,out_id')->select();
        if (!$currentData->isEmpty()){
            $currentData = $currentData->toArray();

            $currentDataIdArr = array_column($currentData,'out_id');
            $currentDataNameKeyArr = array_column($currentData,'name');
            //$diff = array_diff($curlDataIdArr,$currentDataIdArr); //有前后之分，这样比较如果diff不为空，则为当前表中数据缺少新的diff，需要添加
            $diff = array_diff($curlDataNameKeyArr,$currentDataNameKeyArr); //有前后之分，这样比较如果diff不为空，则为当前表中数据缺少新的diff，需要添加
            //dump($curlDataNameKeyArr,$currentDataNameKeyArr,$diff);exit;
            if (!empty($diff)){
                foreach ($diff as $k=>$v){
                    if (isset($curlDataNameArr[$v])){
                        $addNew[$k]['name'] = $curlDataNameArr[$v]['name'];
                        $addNew[$k]['logo'] = $curlDataNameArr[$v]['logo'];
                        $addNew[$k]['address'] = $curlDataNameArr[$v]['address'];
                        $addNew[$k]['introduce'] = Str::strip_html_tags($curlDataNameArr[$v]['introduce']);

                        $addNew[$k]['out_id'] = $curlDataNameArr[$v]['id'];//非零工超市系统自己添加
                    }

                }
            }
            //dump($currentData,$curlDataIdArr);exit;

            foreach ($currentData as $k=>$v){
                if (in_array($v['out_id'],$curlDataIdArr)){
                    //已添加、状态正常，则保留，只更新一般显示数据
                    //已添加、状态为删除状态，重新更新状态为1
                    $saveNew[$k]['id'] = $v['id'];
                    $saveNew[$k]['status'] = 1;
                    if (isset($curlDataArr[$v['out_id']])){
                        $saveNew[$k]['name'] = $curlDataArr[$v['out_id']]['name'];
                        $saveNew[$k]['logo'] = $curlDataArr[$v['out_id']]['logo'];
                        $saveNew[$k]['address'] = $curlDataArr[$v['out_id']]['address'];
                        $saveNew[$k]['introduce'] = Str::strip_html_tags($curlDataArr[$v['out_id']]['introduce']);
                    }
                }else{
                    //库中数据不在最新curl数据中，更新状态为0
                    //还需要额外判断是否系统自己添加的，不能更新状态
                    if($v['out_id'] != 0){
                        $saveNew[$k]['id'] = $v['id'];
                        $saveNew[$k]['status'] = 0;
                    }
                }
            }
        }else{
            //未添加，此次添加
            foreach ($curlData['data']['list'] as $k=>$v){
                $addNew[$k]['name'] = $v['name'];
                $addNew[$k]['logo'] = $v['logo'];
                $addNew[$k]['address'] = $v['address'];
                $addNew[$k]['introduce'] = Str::strip_html_tags($v['introduce']);

                $addNew[$k]['out_id'] = $v['id'];//非零工超市系统自己添加
            }
        }
        //dump($addNew,$saveNew);exit;

        //批量添加newData
        if (!empty($addNew)){
            $addNew = array_values($addNew);
            $daoAdd = $this->saveAll($addNew);
        }else{
            $daoAdd = true;
        }

        //批量更新saveNew
        if (!empty($saveNew)){
            $saveNew = array_values($saveNew);
            $daoSave = $this->saveAll($saveNew);
        }else{
            $daoSave = true;
        }

        if ($daoAdd && $daoSave){
            return true;
        }else{
            return false;
        }
    }

}
